package org.h2.util;


import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.io.*;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by computer on 2017/10/29.
 */
public class LogUtil {
    private static volatile LogUtil instanceLocal;

    private static ExecutorService pool = Executors.newFixedThreadPool(5);
    private static Lock lock = new ReentrantLock();

    /*
    * @param type 1:console 2:打印到文本中
    * */

    public void print(Class cla, Object... objects) {
        LogWorker logWorker = new LogWorker();
        String className = cla.getName();
        String time = DateFormatUtils.format(new Date(), "yyyy-MM-dd'T'HH:mm:ssZZ");
        String context = JSON.toJSONString(objects);
        String log = className + " ：" + time + " : " + context;
        logWorker.setLog(log);
        LogRunnable logRunnable = new LogRunnable(logWorker);
        pool.execute(logRunnable);
    }

    public static synchronized LogUtil init() {
        if (null == instanceLocal) {
            synchronized (LogUtil.class) {
                if (instanceLocal == null) {
                    instanceLocal = new LogUtil();
                }
            }
        }
        return instanceLocal;
    }

    class LogRunnable implements Runnable {
        private LogWorker logWorker;

        public LogRunnable(LogWorker logWorker) {
            this.logWorker = logWorker;
        }

        @Override
        public void run() {
            lock.lock();
            try {
                logWorker.print();
            } catch (Exception e) {
            } finally {
                lock.unlock();
            }
        }
    }

    class LogWorker {
        private String log;
        public void print() throws IOException {
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("D://log.txt", true)));
            bw.write(log); // \r\n即为
            bw.write("\r\n");
            bw.flush(); // 把缓存区内容压入文件
            bw.close(); // 最后记得关闭文件
            System.out.println(log);
        }

        public String getLog() {
            return log;
        }

        public void setLog(String log) {
            this.log = log;
        }

    }
}
